package com.tencent.cloud.iov.flow.presenter.impl;

import com.tencent.cloud.iov.action.IActionListener;
import com.tencent.cloud.iov.flow.loader.ILoader;
import com.tencent.cloud.iov.flow.presenter.IPresenter;

import io.reactivex.Observer;

/**
 * MVP - P 逻辑抽象类
 *
 * 实现视图绑定及解绑、模型数据订阅及取消订阅
 *
 * DATA: P 层接收来自模型层的目标数据类型
 * LOADER: MVP - M
 *
 * @author showxiao
 * @date 2018/3/27
 */

public abstract class BaseFlowPresenter<DATA, LOADER extends ILoader<Observer<DATA>>>
        implements IPresenter {

    private IActionListener mActionListener;
    private LOADER mLoader;
    private Observer<DATA> mObserver;

    @Override
    public void onCreate() {
        // do nothing
    }

    @Override
    public final void setActionListener(IActionListener listener) {
        mActionListener = listener;
    }

    public final IActionListener getActionListener() {
        return mActionListener;
    }

    public final void onAction(String actionId, Object...args) {
        if (mActionListener != null) {
            mActionListener.onAction(actionId, args);
        }
    }

    @Override
    public void startLoader() {
        if (mLoader == null) {
            setLoader(createLoader());
        }
        if (mLoader != null) {
            ensureObserver();
            mLoader.register(mObserver);
            mLoader.loadData();
        }
    }

    @Override
    public void registerLoader() {
        if (mLoader != null) {
            mLoader.register(mObserver);
        }
    }

    @Override
    public void unregisterLoader() {
        if (mLoader != null) {
            mLoader.unregister(mObserver);
        }
    }

    public final void setLoader(LOADER loader) {
        mLoader = loader;
    }

    /**
     * 创建模型层 MVP - M：继承方式
     *
     * 也可通过组合方式进行设置 {@link #setLoader(ILoader)}
     *
     * @return  MVP - M
     */
    protected abstract LOADER createLoader();

    protected final LOADER getLoader() {
        return mLoader;
    }

    private void ensureObserver() {
        if (mObserver == null) {
            setObserver(createObserver());
        }
    }

    public final void setObserver(Observer<DATA> observer) {
        mObserver = observer;
    }

    /**
     * 创建模型目标数据观察者：继承方式
     *
     * 也可通过组合方式进行设置 {@link #setObserver(Observer)}
     *
     * @return 模型目标数据观察者
     */
    protected abstract Observer<DATA> createObserver();

    protected final Observer<DATA> getObserver() {
        return mObserver;
    }

    @Override
    public void stopLoader() {
        if (mLoader != null) {
            mLoader.close();
            mLoader = null;
        }
    }

    @Override
    public void onDestroy() {
        if (mObserver != null) {
            mObserver.onComplete();
            mObserver = null;
        }
        mActionListener = null;
    }

}
